# -*- coding: utf-8 -*-
#
# Copyright (C) 2011  Benjamin Heil
#
# This file is part of Feedmail.
#
# Feedmail is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django import forms
from django.contrib.auth.models import User
from account.models import AccountProfile

class register_form(forms.ModelForm):
    """
    Form to register a new user
    """
    username = forms.RegexField(label=u"Benutzername", max_length=30,
                                regex=r'^\w+$',
                                error_message=u"Der Login-Name darf nur aus Buchstaben, Zahlen und Unterstrichen bestehen")
    password1 = forms.CharField(label=u"Passwort", max_length=64,
                                widget=forms.PasswordInput)
    password2 = forms.CharField(label=u"Passwort wiederholen", max_length=64,
                                widget=forms.PasswordInput)
    email = forms.EmailField(label=u"Mail-Adresse", max_length=128,
                             help_text=u"An diese Adresse wird eine Mail mit einem Aktivierungscode versendet. Dieser Code wird benötigt, um den Account zu aktivieren. Achte also darauf, eine gültige Adresse anzugeben. Du wirst Dich erst einloggen können, sobald Du Deinen Account bestätigt hast.")

    def clean_username(self):
        """
        Checks if this username already exists
        """
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(u"Ein Nutzer mit diesem Namen existiert schon.")

    def clean_email(self):
        """
        Checks if this mail-adress is already in use
        """
        email = self.cleaned_data["email"]
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(u"Diese Mail-Adresse wird schon verwendet!")

    def clean_password2(self):
        """
        Checks that both typed passwords are the same.
        """
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(u"Die beiden Passwörter stimmen nicht überein")
        return password2

    def save(self, commit=True, *args, **kwargs):
        """
        Saves the new user and creates a new user account associated with the new user.
        """
        user = super(register_form, self).save(commit=False, *args, **kwargs)
        user.set_password(self.cleaned_data["password1"])
        user.email = self.cleaned_data['email']
        user.is_active = False
        if commit:
            user.save()
        profile = AccountProfile.objects.create(user=user)
        profile.save()
        return user

    class Meta:
        model = User
        fields = ("username",)

class profile_form(forms.Form):
    """
    Form to edit a user profile.
    """
    username = forms.RegexField(label=u"Login-Name", max_length=30,
                                regex=r'^\w+$',
                                error_message=u"Der Login-Name darf nur aus Buchstaben, Zahlen und Unterstrichen bestehen")
    email = forms.EmailField(label=u"Mail-Adresse", max_length=128,
                             help_text=u"Wenn Du Deine Mail-Adresse ändern willst, musst Du die neue bestätigen. An diese Adresse wird eine Mail mit einem Aktivierungscode versendet.")

    def save(self, user):
        """
        Saves changes in user data and profile.
        """
        user.email = self.cleaned_data['email']
        user.username = self.cleaned_data['username']
        #p = user.get_profile()
        #p.save()
        user.save()

class resend_activation_mail_form(forms.Form):
    email = forms.EmailField(label=u'Mail-Adresse', max_length=128)

class delete_my_account_form(forms.Form):
    confirmation = forms.BooleanField(label=u"Ja, meinen Account unwiderruflich löschen",
                                      required=False, initial=False)
